12% completed
Here is the step-by-step system design for Netflix.
1. Problem Definition and Scope
We are designing a global Video on Demand (VOD) streaming service. The goal is to allow millions of users to browse a large catalog of movies and TV shows and stream them instantly on various devices (TV, mobile, web) with high quality and minimal buffering.
Main User Groups:
-
Viewers: Users who discover content and watch videos.
-
Content Operations (Admins): Internal teams who upload raw video masters and manage metadata.
Scope:
- In Scope:
-
Content Ingestion: Uploading, processing, and distributing video files.
-
Playback (Data Plane): Streaming video to the client with low latency.
-
Discovery (Control Plane): Browsing and searching the catalog.
-
User History: Tracking watch progress to resume playback.
-
- Out of Scope: Billing, payments, user sign-up flows, and complex recommendation algorithms (we will assume a recommendation service provides a list of video IDs).
2. Clarify functional requirements
Must Have:
-
Video Ingestion: Admins can upload high-quality raw video files.
-
Transcoding: The system automatically converts raw video into multiple formats (codecs) and resolutions (4K, 1080p, mobile) to support different devices and network speeds.
-
Playback: Users can start playing a video with low latency (< 2 seconds).
-
Adaptive Bitrate Streaming: Video quality automatically adjusts in real-time based on the user's bandwidth (e.g., switching from 4K to 720p).
-
Resume Capability: Users can pause on one device and resume from the same second on another.
-
Search: Users can find titles by text search.
Nice to Have:
-
Offline Viewing: Downloading content for later.
-
Multiple Profiles: Distinct history for different users under one account.
3. Clarify non-functional requirements
Scale:
-
Users: ~200 Million Daily Active Users (DAU).
-
Traffic Pattern: Extremely Read-Heavy. The ratio of viewing (reads) to uploading (writes) is massive (e.g., 100,000:1).
-
Global Reach: Must serve users worldwide with low latency.
Performance:
-
Latency: Fast browsing response (< 200ms). Fast time-to-first-frame for video (< 2s).
-
Availability: High availability (99.99%) for playback. If the "My List" feature breaks, users should still be able to play videos from the home screen.
Consistency:
-
Metadata: Eventual consistency is acceptable. If a new movie description takes a minute to propagate, it's fine.
-
Watch History: Needs to be fast and fairly consistent so users can switch devices quickly, but eventual consistency (seconds lag) is acceptable.
4. Back of the envelope estimates
Traffic Estimates:
- 200 million DAU.
- Peak Traffic: Assume 10-15% of users are active during prime time = ~30 million concurrent streams.
Bandwidth Estimates (The critical constraint):
- Standard Definition (SD) = ~1 GB/hour.
- High Definition (HD) = ~3 GB/hour.
- 4K = ~7 GB/hour.
- Average = ~4 Mbps (Megabits per second).
- Peak Bandwidth: 30 million streams * 4 Mbps = 120 Terabits per second (Tbps).
- Conclusion: This is an enormous amount of data. We cannot serve this from a central cloud region. We require a massive, distributed Content Delivery Network (CDN).
Storage Estimates:
- Catalog: 15,000 titles.
- Size: 1 raw master file = 100 GB.
- Transcoding: We generate ~50 versions per title (combinations of resolution + codec + audio). Total size per title ≈ 150 GB.
- Total Content Storage: 15,000 * 150 GB = 2.25 Petabytes.
- Conclusion: Storage is large but manageable in standard object storage (S3). Bandwidth is the harder problem.
5. API design
We will use a REST API for the Control Plane (browsing/metadata). The Data Plane (video) uses streaming protocols (HLS/DASH) over HTTP.
1. Get Home Feed
- GET /v1/feed
- Params: profile_id
- Response: JSON list of "Shelves" (e.g., "Trending", "Comedy"), each containing a list of video summaries.
2. Get Video Metadata
- GET /v1/videos/{video_id}
- Response: Title, description, cast, maturity rating, and episodes (if TV show).
3. Start Playback Session
- POST /v1/playback/init
- Params: video_id, device_type
- Response:
- playback_url: URL to the Manifest File on the CDN.
- drm_token: Token to decrypt the video content.
- timestamp: Time to resume from (e.g., 120 seconds).
4. Update Watch History (Heartbeat)
- POST /v1/users/history
- Params: video_id, timestamp
- Response: 200 OK. (Sent every ~10 seconds).
6. High level architecture
We divide the architecture into two distinct parts: the Control Plane (AWS/Cloud) and the Data Plane (Open Connect/CDN).
Component Explanation:
- Client: Handles UI and the Adaptive Bitrate player logic.
- API Gateway: Routes API requests, handles auth and rate limiting.
- Control Plane Microservices:
- Metadata Service: Serves static movie info.
- User Service: Manages profiles and watch history.
- Playback Service: Verifies subscription and determines the best CDN node for the user (Steering).
- Open Connect (CDN): Netflix's custom hardware placed inside ISP data centers globally. It stores video chunks physically close to users to save bandwidth and reduce latency.
- S3 (Source of Truth): Stores the master copies of all video files.
7. Data model
We use a polyglot persistence strategy.
1. User History (Write-Heavy NoSQL)
- Technology: Cassandra.
- Why: We have millions of users sending heartbeats every 10 seconds. We need massive write throughput and horizontal scalability.
- Schema:
- user_id (Partition Key)
- video_id (Clustering Key)
- last_watched_timestamp
- status (Started, Finished)
2. Movie Metadata (Read-Heavy)
- Technology: PostgreSQL (or Cassandra for scale).
- Why: Data is structured (Movies have Actors, Episodes belong to Seasons). Reads vastly outnumber writes.
- Schema:
- videos: id, title, description, release_year.
- assets: video_id, cdn_url, file_size, resolution.
3. Video Files (Object Storage)
- Technology: AWS S3.
- Why: Cheap, durable storage for large blobs (video files).
8. Core Flows End-to-End
To understand the system deep down, we need to follow the data. We will look at three critical lifecycles:
-
The Write Path (Ingestion): How a raw movie file becomes streamable.
-
The Read Path (Playback): How the client intelligently streams video.
-
The Async Path (History): How we track progress without crashing the database.
Flow 1: Content Ingestion Pipeline (The Write Path)
Goal: Turn one massive, raw movie file into thousands of small, optimized files distributed globally.
In a typical web app, a file upload is a simple synchronous process. At Netflix, ingesting a movie is a massive parallel manufacturing pipeline. We use a Workflow Orchestrator (like Netflix Conductor) to manage this complexity.
Step 1: Upload & Validation
-
Action: The Content Operations team uploads the raw "Mezzanine" (Master) file to AWS S3. These files are huge (TB size) and cinema-quality.
-
Validation: A background service immediately scans the file metadata. It checks for corruption, missing audio tracks, or sync issues. We "fail fast" here to avoid wasting compute resources on a bad file.
Step 2: Chunking (The Parallelism Strategy)
-
The Problem: Transcoding a 2-hour 4K movie on a single server is slow and fragile. If the server crashes at 99%, the entire job is lost.
-
The Solution: The Orchestrator triggers a "Chunking" service that splits the video into small, 4-minute segments.
-
Fan-Out: A single movie is broken into ~30 distinct chunks. This allows us to process the entire movie in parallel across 30 different servers simultaneously.
Step 3: Parallel Transcoding (The "Encoding Ladder")
-
Action: The Orchestrator schedules these chunks across thousands of worker nodes (EC2 instances).
-
The Job: Each worker converts its chunk into ~50 different formats, known as the Encoding Ladder:
-
Resolutions: 4K, 1080p, 720p, and mobile-optimized SD.
-
Codecs: H.264 (older devices), HEVC (Smart TVs), and AV1 (Android/Web).
-
Result: One raw chunk becomes ~50 optimized files.
Step 4: Packaging & Proactive Distribution (The "Push" Model)
-
Packaging: The chunks are encrypted (DRM) and "packaged" into streaming containers (like DASH or HLS). A Manifest File is created (see Flow 2).
-
The Push: Unlike generic CDNs that cache content after a user requests it ("Pull"), Netflix predicts popularity.
-
Action: During off-peak hours (e.g., 4 AM), the system copies these files from S3 to Open Connect Appliances (OCAs), which are custom servers installed physically inside ISP data centers (like Comcast or Verizon), so the content is already waiting down the street from the user before they press play."
Flow 2: Playback (The Read Path)
Goal: Connect the user to the best server and stream video without buffering.
We divide this into the Control Plane (AWS - deciding where to play) and the Data Plane (Open Connect - actually sending the video).
Phase A: Playback Initialization (The Control Plane) Before the video starts, the Client negotiates with the Backend.
- The Play Request:
- User clicks "Play." The Client sends
POST /playback/initwithvideo_idanddevice_type.
- Auth & Licensing:
- The Playback Service verifies the subscription and checks region locking.
- It communicates with the Key Management Service (KMS) to generate a DRM License, a secure key the device needs to decrypt the video.
- Steering (The Traffic Cop):
-
The Steering Service must pick the single best Open Connect server for this user.
-
It analyzes:
-
Proximity: Which ISP data center is the user connected to?
-
Health: Is that server currently overloaded?
-
Inventory: Does that server specifically hold the files for this movie?
-
Response: The API returns a URL to the Manifest File hosted on that optimal server.
Phase B: Adaptive Streaming (The Data Plane) Once the Client has the Manifest, the Backend steps out. The Client talks directly to the CDN.
- The Manifest (The "Menu"):
- The Client downloads the Manifest file (
.m3u8). Think of this as a restaurant menu. It tells the player: - "I have 4K chunks available at these URLs..."
- "I have 720p chunks available at these URLs..."
- Adaptive Bitrate Streaming (ABS) Loop:
- The intelligence lives in the Client, not the Server.
- Step 1 (Download): The client downloads the first 4-second chunk.
- Step 2 (Measure): It calculates: "That took 0.1 seconds. My speed is 50 Mbps."
- Step 3 (Decide): "The Manifest says 4K needs 15 Mbps. I have 50. I will request the next chunk in 4K."
- Step 4 (Adapt): Suddenly, someone turns on the microwave, and WiFi slows down. The client detects the drop and requests the next chunk in 720p.
- Result: The user sees the quality dip (pixelation), but the video never stops to buffer.
Flow 3: Watch History (The Async Path)
Goal: Save user progress without slowing down the viewing experience.
The Challenge: If 10 million users are watching simultaneously, and every client sends a status update every 10 seconds, a standard database (like MySQL) would crash under the write load.
Step 1: Heartbeats
-
Action: Every ~10 seconds, the client sends a lightweight "Heartbeat" signal to the API.
-
Payload:
{ userId: 123, videoId: 555, timestamp: 12m:30s }.
Step 2: Write Buffering (Fire-and-Forget)
-
The Firehose: The API Gateway does not write to the database. It pushes the event immediately to a high-throughput message queue (Kafka).
-
Benefit: This decouples the client from the database. The client gets a "200 OK" instantly, even if the database is busy.
Step 3: Aggregation & Persistence
-
Stream Processing: A background worker (using a tool like Apache Flink) reads from the Kafka stream.
-
Deduplication: If a user sends 6 heartbeats in one minute, we only care about the last one (the latest timestamp). The processor discards the intermediate 5.
-
Final Write: The aggregated state is written to Cassandra.
-
Why Cassandra? It is optimized for massive write throughput, making it perfect for this "write-heavy" workload.
9. Caching and read performance
1. Content Delivery Network (Open Connect)
- Strategy: Proactive Caching (Push). Unlike generic CDNs that cache on "miss," Netflix predicts popularity. Popular shows are pushed to ISP servers during off-peak hours (4 AM) so they are ready for prime time.
- Long Tail: For older, unpopular movies, we might use a standard "Pull" model where the CDN fetches from S3 on demand.
2. Metadata Caching (Memcached/EVCache)
- Strategy: Cache-Aside.
- Data: Movie titles, descriptions, and user profiles.
- In-Memory: Keeping this data in RAM ensures browsing is snappy (< 200ms).
10. Storage, indexing, and media
Video Storage Strategy:
- S3: Durable storage for "Golden Copies."
- Open Connect: Ephemeral storage for delivery. If a drive fails in an ISP data center, we just re-copy data from S3 or a neighbor node.
Search Indexing:
- Elasticsearch:
- We ingest metadata changes into Elasticsearch.
- Supports fuzzy search (e.g., "Spidrman" -> "Spider-Man").
- Supports faceted search (by Genre, Year, Actor).
Streaming Protocols:
- We use HLS (HTTP Live Streaming) or MPEG-DASH.
- These protocols break video into small files. This allows the client to switch quality every few seconds seamlessly (Adaptive Bitrate).
11. Scaling strategies
1. Database Sharding:
- Cassandra (History): Sharded by user_id. All history for User A is on the same node partition. This makes writes fast and lookups simple.
- Metadata: Can be replicated across regions. Since the catalog is small (< 1TB of text), we can replicate the full dataset to all regions for fast local reads.
2. Async Processing (Write Buffering):
- The "Heartbeat" write volume is massive.
- Instead of writing directly to DB, the API pushes heartbeats to Kafka.
- Workers read from Kafka, deduplicate (only keep the latest timestamp per minute), and batch write to Cassandra. This protects the DB from spikes.
3. Bulkhead Pattern:
- We isolate services. If the "Recommendations" service is overloaded, it doesn't crash the "Playback" service. The UI just shows a generic "Popular Movies" list instead of "Top Picks for You."
12. Reliability, failure handling, and backpressure
1. Chaos Engineering:
- We use tools like Chaos Monkey to intentionally kill services in production. This forces engineers to design systems that auto-recover.
2. Circuit Breakers:
- If the "Reviews Service" is slow, the API Gateway stops calling it and returns an empty review list immediately. This prevents a backlog of waiting requests from crashing the whole system.
3. Graceful Degradation:
- If the 4K video files are corrupted or the 4K CDN servers are overloaded, the manifest returned to the client will simply exclude the 4K option. The user watches in 1080p without realizing there was a failure.
13. Security, privacy, and abuse
1. Digital Rights Management (DRM):
- Video chunks are encrypted (AES-128).
- The client must obtain a license from a DRM server (Widevine/FairPlay) to decrypt frames in the device's secure memory.
2. Signed URLs:
- CDN links are not public. They contain a token signed with a secret key.
- The token validates the user's IP and expires after a few hours, preventing link sharing.
3. Privacy:
- User watch history is sensitive data. It is encrypted at rest, and access is strictly controlled (GDPR compliance).
14. Bottlenecks and next steps
Current Bottlenecks:
- ISP Capacity: If a specific ISP (e.g., Comcast in a specific city) is congested, users will buffer regardless of our backend.
- Global Replication: Syncing user "resume points" across regions (e.g., travel from US to Europe) has a delay due to the speed of light.
Next Steps:
- Better Codecs: Implement AV1. It provides the same video quality at 30% less bitrate, saving massive bandwidth costs.
- Predictive Prefetching: Pre-load the first 30 seconds of the "Next Episode" to the user's device while they are watching the credits of the current one, ensuring instant start.
Summary
- We designed a read-heavy system relying on a custom Data Plane (Open Connect) to handle 100+ Tbps of traffic.
- The Control Plane uses Microservices and Cassandra to handle millions of concurrent users.
- Key technologies include Adaptive Bitrate Streaming, Proactive Caching, and Kafka for buffering write bursts.
On this page
1. Problem Definition and Scope
2. Clarify functional requirements
3. Clarify non-functional requirements
4. Back of the envelope estimates
5. API design
6. High level architecture
7. Data model
- Core Flows End-to-End
Flow 1: Content Ingestion Pipeline (The Write Path)
Flow 2: Playback (The Read Path)
Flow 3: Watch History (The Async Path)
9. Caching and read performance
10. Storage, indexing, and media
11. Scaling strategies
12. Reliability, failure handling, and backpressure
13. Security, privacy, and abuse
14. Bottlenecks and next steps
Summary